package com.haixiaoke.saas.enterprise.contract.controller;

import java.text.SimpleDateFormat;
import java.util.List;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.fasc.open.api.v5_1.res.template.SignTemplateListInfo;
import com.fasc.open.api.v5_1.res.template.SignTemplateListRes;
import com.haixiaoke.saas.common.annotation.Log;
import com.haixiaoke.saas.common.annotation.RepeatSubmit;
import com.haixiaoke.saas.common.constant.PlatformConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.page.PageDomain;
import com.haixiaoke.saas.common.core.page.TableDataInfo;
import com.haixiaoke.saas.common.core.page.TableSupport;
import com.haixiaoke.saas.common.enums.BusinessType;
import com.haixiaoke.saas.contract.domain.Contract;
import com.haixiaoke.saas.contract.service.IContractService;
import com.haixiaoke.saas.fadada.service.FaDaDaService;
import com.haixiaoke.saas.system.BaseController;
import com.haixiaoke.saas.system.framework.security.util.SecurityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 合同Controller
 * 
 * @author panda
 * @date 2025-06-26
 */
@RestController
@RequestMapping("/enterprise/contract/contract")
public class EnterpriseContractController extends BaseController {
    @Autowired
    private IContractService contractService;
    @Autowired
    private FaDaDaService faDaDaService;

    /**
     * 查询合同列表
     */
    @PreAuthorize("@ss.hasPermi('enterprise:contract:page')")
    @GetMapping("/page")
    public TableDataInfo list(Contract contract) {
        startPage();
        contract.setTenantType(getLoginUser().getTenantId());
        if (StrUtil.equals(PlatformConstants.PC_BUSINESS, getLoginUser().getPlatform())) {
            contract.setTenantIds(getTenantIds());
        }
        if (StrUtil.equals(PlatformConstants.MP_WECHAT_BUSINESS, getLoginUser().getPlatform())) {
            contract.setTenantId(getLoginUser().getTenantId());
        }
        List<Contract> list = contractService.selectContractList(contract);
        return getDataTable(list);
    }

    /**
     * 查询电子合同模板列表
     */
    @GetMapping("/electronicTemplates")
    public AjaxResult electronicVisaPage(@RequestParam(required = false) String templateName) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        SignTemplateListRes signTemplateList = faDaDaService.getSignTemplateList(pageDomain.getPageNum(), pageDomain.getPageSize(), templateName);
        // 创建一个SimpleDateFormat对象，定义目标日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (CollectionUtil.isNotEmpty(signTemplateList.getSignTemplates())) {
            for (SignTemplateListInfo signTemplateListInfo : signTemplateList.getSignTemplates()) {
                signTemplateListInfo.setCreateTime(sdf.format(Long.valueOf(signTemplateListInfo.getCreateTime())));
                signTemplateListInfo.setUpdateTime(sdf.format(Long.valueOf(signTemplateListInfo.getUpdateTime())));
            }
        }
        return success(signTemplateList);
    }

    /**
     * 获取合同详细信息
     */
    @PreAuthorize("@ss.hasPermi('enterprise:contract:query')")
    @GetMapping(value = "/{contractId}")
    public AjaxResult getInfo(@PathVariable("contractId") String contractId) {
        return success(contractService.selectContractByContractId(contractId));
    }

    /**
     * 查询该房屋被租赁的时间段
     * @param houseId
     * @return
     */
   @GetMapping("/checkTime/{houseId}")
    public AjaxResult checkTime(@PathVariable("houseId") String houseId) {
        return success(contractService.checkTime(houseId));
    }

    /**
     * 获取预览电子合同内容链接
     */
    @PreAuthorize("@ss.hasPermi('enterprise:contract:query')")
    @PostMapping(value = "/previewUrl")
    public AjaxResult electronicVisaPreviewUrl(@RequestBody Contract contract) {
        return contractService.selectContractPreviewUrl(contract);
    }

    /**
     * 新增合同
     */
    @PreAuthorize("@ss.hasPermi('enterprise:contract:add')")
    @Log(title = "合同", businessType = BusinessType.INSERT)
    @PostMapping
    @RepeatSubmit
    public AjaxResult add(@RequestBody Contract contract) {
        contract.setCreateBy(getUsername());
        contract.setTenantId(getLoginUser().getTenantId());
        return contractService.insertContract(contract);
    }

    /**
     * 上传合同图片,签署纸质合同
     *
     * @param contract
     * @return
     */
    @PreAuthorize("@ss.hasPermi('enterprise:contract:edit')")
    @Log(title = "合同签署纸质合同", businessType = BusinessType.UPDATE)
    @PutMapping("/uploadContractImage")
    @RepeatSubmit
    public AjaxResult uploadContractImage(@RequestBody Contract contract) {
        contract.setUpdateBy(getUsername());
        contract.setTenantId(getLoginUser().getTenantId());
        return contractService.uploadContractImage(contract);
    }

    /**
     * 合同入住
     * @param contractId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('enterprise:contract:edit')")
    @Log(title = "合同入住", businessType = BusinessType.UPDATE)
    @PutMapping("/checkIn/{contractId}")
    @RepeatSubmit
    public AjaxResult checkIn(@PathVariable String contractId) {
        return contractService.checkIn(contractId, getUsername(), getLoginUser().getTenantId());
    }

    /**
     * 签署电子合同
     */
    @PreAuthorize("@ss.hasPermi('enterprise:contract:edit')")
    @Log(title = "租客合同签署", businessType = BusinessType.UPDATE)
    @PutMapping("/signing")
    @RepeatSubmit
    public AjaxResult signing(@RequestBody Contract contract) {
        contract.setTenantId(getLoginUser().getTenantId());
        return contractService.signingContract(contract, true);
    }
}
